package apis

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	"net/http"
	modelsadmin "tuowei.com/app/admin/models"
	serviceadmin "tuowei.com/app/admin/service"
	dtoadmin "tuowei.com/app/admin/service/dto"
	"tuowei.com/app/api/models"
	"tuowei.com/app/api/service"
	"tuowei.com/app/api/service/dto"
	"tuowei.com/common/actions"
)

type SysScore struct {
	api.Api
}

func (e SysScore) GetPages(c *gin.Context) {
	s := service.SysScore{}
	req := dto.SysScoreGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	if req.BuyerId == 0 {
		req.BuyerId = user.GetUserId(c)
	}
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	var count int64
	list := make([]models.SysScore, 0)

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}
	listresp := make([]GetPagesScoreResp, 0)
	for _, sc := range list {
		sr := GetPagesScoreResp{}
		sr.Id = sc.Id
		sr.BuyerId = sc.BuyerId
		sr.OrderNumber = sc.OrderNumber
		sr.ScoreChange = sc.ScoreChange
		sr.Change = sc.Change
		sr.OrderType = sc.OrderType
		sr.CreatedTime = sc.CreatedAt.Format("2006.01.02 15:04:05")
		sr.Subject = sc.Subject
		sr.Name = sc.Name
		sr.Cover = sc.Cover
		sr.Introduction = sc.Introduction

		listresp = append(listresp, sr)
	}

	e.PageOK(listresp, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// 增加积分记录
func (score SysScore) AddScore(ctx *gin.Context) {
	s := service.SysScore{}
	req := dto.SysScoreInsertReq{}
	err := score.MakeContext(ctx).
		MakeOrm().
		Bind(&req, binding.Default(ctx.Request.Method, ctx.ContentType())).
		MakeService(&s.Service).Errors
	if err != nil {
		score.Logger.Error(err)
		score.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	//数据权限检查
	p := actions.GetPermissionFromContext(ctx)
	// 设置创建人
	req.SetCreateBy(user.GetUserId(ctx), user.GetUserName(ctx))
	if req.BuyerId == 0 {
		req.BuyerId = user.GetUserId(ctx)
	}
	switch req.OrderType {
	case "OnlineOrder", "LiveOrder":
		var data modelsadmin.OnlineOrder
		err = s.Orm.Debug().Table(data.TableName()).Where("order_number = ?", req.OrderNumber).
			First(&data).Error
		if err != nil {
			score.Logger.Error(err)
			score.Error(500, err, err.Error())
			return
		}
		s1 := serviceadmin.SysOrder{}
		s1.Orm = s.Orm
		req1 := dtoadmin.SysOnlineOrderDetailRequest{}
		req1.Id = data.Id
		detail := new(modelsadmin.OnlineOrder)
		detail.Id = data.Id
		err = s1.GetOnlineOrderDetail(&req1, p, detail)
		if err != nil {
			score.Error(500, err, err.Error())
			return
		}
		if len(detail.Course) >= 1 {
			req.Subject = detail.Course[0].Subject
			req.Name = detail.Course[0].Name
			req.Cover = detail.Course[0].Cover
			req.Introduction = detail.Course[0].Introduction
		}

	case "MaterialOrder":
		var data modelsadmin.MaterialOrder
		err = s.Orm.Debug().Table(data.TableName()).Where("order_number = ?", req.OrderNumber).
			First(&data).Error
		if err != nil {
			score.Logger.Error(err)
			score.Error(500, err, err.Error())
			return
		}

		s2 := serviceadmin.SysOrder{}
		s2.Orm = s.Orm
		req2 := dtoadmin.SysMaterialOrderDetailRequest{}
		req2.Id = data.Id
		detail := new(modelsadmin.MaterialOrder)
		detail.Id = data.Id
		err = s2.GetMaterialOrderDetail(&req2, p, detail)
		if err != nil {
			score.Logger.Error(err)
			score.Error(500, err, err.Error())
			return
		}
		if len(detail.Material) >= 1 {
			req.Subject = detail.Material[0].Subject
			req.Name = detail.Material[0].Name
			req.Cover = detail.Material[0].Cover
			req.Introduction = detail.Material[0].Introduction
		}

	}
	err = s.Insert(&req)
	if err != nil {
		score.Logger.Error(err)
		score.Error(500, err, err.Error())
		return
	}
	score.OK(req.GetId(), "创建成功")
}

func (score SysScore) AddScoreInternal(ctx *gin.Context, req dto.SysScoreInsertReq) {
	s := service.SysScore{}
	err := score.MakeContext(ctx).
		MakeOrm().
		MakeService(&s.Service).Errors
	if err != nil {
		score.Logger.Error(err)
		score.Error(http.StatusBadRequest, err, err.Error())
		return
	}
	//数据权限检查
	p := actions.GetPermissionFromContext(ctx)
	// 设置创建人
	req.SetCreateBy(user.GetUserId(ctx), user.GetUserName(ctx))
	if req.BuyerId == 0 {
		req.BuyerId = user.GetUserId(ctx)
	}
	switch req.OrderType {
	case "OnlineOrder", "LiveOrder":
		var data modelsadmin.OnlineOrder
		err = s.Orm.Debug().Table(data.TableName()).Where("order_number = ?", req.OrderNumber).
			First(&data).Error
		if err != nil {
			score.Logger.Error(err)
			score.Error(500, err, err.Error())
			return
		}
		s1 := serviceadmin.SysOrder{}
		s1.Orm = s.Orm
		req1 := dtoadmin.SysOnlineOrderDetailRequest{}
		req1.Id = data.Id
		detail := new(modelsadmin.OnlineOrder)
		detail.Id = data.Id
		err = s1.GetOnlineOrderDetail(&req1, p, detail)
		if err != nil {
			score.Error(500, err, err.Error())
			return
		}
		if len(detail.Course) >= 1 {
			req.Subject = detail.Course[0].Subject
			req.Name = detail.Course[0].Name
			req.Cover = detail.Course[0].Cover
			req.Introduction = detail.Course[0].Introduction
		}

	case "MaterialOrder":
		var data modelsadmin.MaterialOrder
		err = s.Orm.Debug().Table(data.TableName()).Where("order_number = ?", req.OrderNumber).
			First(&data).Error
		if err != nil {
			score.Logger.Error(err)
			score.Error(500, err, err.Error())
			return
		}

		s2 := serviceadmin.SysOrder{}
		s2.Orm = s.Orm
		req2 := dtoadmin.SysMaterialOrderDetailRequest{}
		req2.Id = data.Id
		detail := new(modelsadmin.MaterialOrder)
		detail.Id = data.Id
		err = s2.GetMaterialOrderDetail(&req2, p, detail)
		if err != nil {
			score.Logger.Error(err)
			score.Error(500, err, err.Error())
			return
		}
		if len(detail.Material) >= 1 {
			req.Subject = detail.Material[0].Subject
			req.Name = detail.Material[0].Name
			req.Cover = detail.Material[0].Cover
			req.Introduction = detail.Material[0].Introduction
		}

	}
	err = s.Insert(&req)
	if err != nil {
		score.Logger.Error(err)
		score.Error(500, err, err.Error())
		return
	}
	score.OK(req.GetId(), "创建成功")
}
func (e SysScore) GetSum(c *gin.Context) {
	s := service.SysScore{}
	req := dto.SysScoreGeAllReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	if req.BuyerId == 0 {
		req.BuyerId = user.GetUserId(c)
	}
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	var count int64
	list := make([]models.SysScore, 0)

	err = s.GetAll(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}
	sum := 0.00
	for _, ll := range list {
		switch ll.Change {
		case 1:
			sum = sum + ll.ScoreChange
		default:
			sum = sum - ll.ScoreChange
		}
	}
	if sum < 0 {
		sum = 0.00
	}
	e.OK(sum, "查询成功")
}

type GetPagesScoreResp struct {
	models.SysScore
	CreatedTime string `json:"created_time" gorm:"comment:创建时间"`
}
